﻿using System;
using System.Globalization;
using System.Windows.Forms;
using Data.Common;
using Data.Enum;
using Data.Model;
using DataAccess.SystemManage;
using Ninject;
using WinForm.Helper;

namespace WinForm.Dialog
{
    public partial class EditSUser : Form
    {
        private static readonly IKernel Kernel = new StandardKernel(new DbModule());
        private readonly ISysUser _sysUser = Kernel.Get<ISysUser>();

        public EditSUser()
        {
            InitializeComponent();
        }

        public EditSUser(int id)
        {
            InitializeComponent();

            if (id > 0)
            {
                lbUserid.Text = id.ToString(CultureInfo.InvariantCulture);
                Text = "编辑用户";
                txtPassword.Visible = false;
                txtRePassword.Visible = false;
                labelPassword.Visible = false;
                labelRePassword.Visible = false;

                ResultInfo<jsh_user> u = _sysUser.GetUser(id);
                if (u != null)
                {
                    txtUserName.Text = u.Obj.username;
                    lbUserid.Text = u.Obj.id.ToString();
                }
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            try
            {
                //TODO:
                var user = new jsh_user
                {
                    id = Converts.ConvertToInt(lbUserid.Text),
                    displayname = "",
                    username = txtUserName.Text
                };

                if (txtPassword.Text != txtRePassword.Text)
                {
                    MyMessageBox.ShowMessageBoxInfo("请输入一致的密码！");
                    return;
                }

                user.password = ParseMD5String.GetMD5Password(txtPassword.Text);
                ResultInfo<int> id = _sysUser.CreateUpdateUser(user);
                if (id.ResultNumber == ResultEnum.Success)
                {
                    if (!string.IsNullOrEmpty(lbUserid.Text))
                    {
                        MyMessageBox.ShowMessageBoxInfo("更新用户成功！");
                    }
                    if (string.IsNullOrEmpty(lbUserid.Text))
                    {
                        MyMessageBox.ShowMessageBoxInfo("新增用户成功！");
                    }

                    DialogResult = DialogResult.OK;
                }
                else
                {
                    MyMessageBox.ShowMessageBoxInfo(id.Describe);
                }
            }
            catch (Exception)
            {
                MyMessageBox.ShowMessageBoxInfo("保存失败！");
            }
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            Close();
            Dispose();
        }
    }
}